<?php

error_reporting(0);

/* ksqurl / index.php */
/* landing page */
/* updated feb 4 2011 by Kevan */

require_once 'includes/config.php'; // settings
require_once 'includes/gen.php'; // url generation and location
session_start();

$perma = parse_url( $_SERVER['REQUEST_URI'] );
$_PERMA = explode( "/", $perma['path'], 3 );
@array_shift( $_PERMA );

if (empty($_SERVER['QUERY_STRING']))
	{
		$qs = '';
	}else{
		$qs = '?'.$_SERVER['QUERY_STRING'].'';
	}

$url = new url();
$msg = '';

// if the form has been submitted
if ( isset($_POST['longurl']) )
{
	// escape bad characters from the users url
	$longurl = trim(mysql_escape_string($_POST['longurl']));
	
	//See if they put something in the text field
	$plain = trim(mysql_escape_string($_POST['plain']));
	
	// set the protocol to not ok by default
	$protocol_ok = false;
		
	// Check phishtank.com to see if this is a possible scam site
	$ptdata = phishtank($longurl);

	// if there's a list of allowed protocols, 
	// check to make sure its all cool
	if ( count($allowed_protocols) )
	{
		foreach ( $allowed_protocols as $ap )
		{
			if ( strtolower(substr($longurl, 0, strlen($ap))) == strtolower($ap) )
			{
				$protocol_ok = true;
				break;
			}
		}
	}
	else // if there's no protocol list, fuck all that
	{
		$protocol_ok = true;
	}

	$plaincheck = check_plain($plain);
	
// If theres a bad custom name list check to make sure this is allowed
	if ( count($badcustom) )
	{
		foreach ( $badcustom as $bc )
		{
			if ( strtolower(substr($plain, 0, strlen($bc))) == strtolower($bc) )
			{
				$custom_bad = true;
				break;
			}
		}
	}
	else // if there's no badcustom list, fuck all that
	{
		$custom_bad = false;
	}
	// Build link or error message
	if ( $protocol_ok && $url->add_url($longurl, $plain) && $plaincheck && $custom_bad != true && $ptdata['results']['in_database'] !=1 )
	{
		$id = $url->get_id($longurl);
		if ( REWRITE ) // mod_rewrite style link
		{
			$url = 'http://'.$_SERVER['SERVER_NAME'].dirname($_SERVER['PHP_SELF']).''.$id;
		}
		else // regular GET style link
		{
			$url = 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'].'?id='.$id;
		}
 		// if good output url
                $msg = '<br/><div class=success-display id="d_clip_button" style=\"display:block;\" \">Here you go: '.$url.' <br /><i><div class="clicktocopy">Click to copy</div></i> <script language="JavaScript">var clip = new ZeroClipboard.Client();clip.setText( \''.$url.'\' ); $(window).load(function(){ clip.glue( \'d_clip_button\' ); }); </script></div><br /> <a href="'.INSTALL_PATH.'qr.php?id='.$id.'"  class="popup"><IMG SRC="qr.png" ALT="Get QR Code"></a>&nbsp;<a href="http://twitter.com/share" class="twitter-share-button" data-url="'.$url.'" data-text="I\'m sharing this short link from '.APP_NAME.'." data-counturl="'.$url.'" data-count="none">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>';
		$msg .= ' <a href="javascript:void(0)"onclick="window.open(\'http://www.facebook.com/sharer.php?u='.urlencode($url).'\',\'linkname\',\'height=450, width=600,scrollbars=no toolbar=no,status=no,resizable=0,menubar=no\')"><IMG SRC="facebook.gif" ALT="Share of Facebook"></a>';
		$msg .=' <a href="https://m.google.com/app/plus/x/?v=compose&content=I wanted to share this link from '.APP_NAME.' - '.$url.'" onclick="window.open(\'https://m.google.com/app/plus/x/?v=compose&content=I wanted to share this link from '.urlencode(APP_NAME).' - '.urlencode($url).'\',\'gplusshare\',\'width=450,height=300,left=\'+(screen.availWidth/2-225)+\',top=\'+(screen.availHeight/2-150)+\'\');return false;"><img src="gplus.png"  alt="Share on Google+" title="Share on Google+"></a>';

	}
	elseif ( !$protocol_ok )
	{
		$msg = '<p class="error"></p>';
	}
	elseif(!$plaincheck) {
		$msg = '<br/><div class=error-display id=error-display style=\"display:block;\" \">Sorry. That custom name is already in use.</div>';
	}
		elseif($custom_bad) {
		$msg = '<br/><div class=error-display id=error-display style=\"display:block;\" \">Sorry. That custom name is not allowed.</div>';
	}
	elseif ( $ptdata['results']['in_database'] == 1  )
	{
		$msg = '<br/><div class=error-display id=error-display style-\"display:block;\" \">This is a suspected phishing site! Please visit <a href="'.$ptdata['results']['phish_detail_page'].'">'.$ptdata['results']['phish_detail_page'].'</a> for more info.</div>';
	}
	else // something broken
	{
		$msg = '<br/><div class=error-display id=error-display style=\"display:block;\" \">Something broke. Try again?</div>';
	}
}
else // if just linked, no submission, look for an id to redirect to
{
        if ( isset($_GET['disabled']) )
        {
                $msg = '<br/><div class=error-display id=error-display style=\"display:block;\" \">This link was disabled by its creator.</div>';
        }

	elseif ( isset($_PERMA[0]) ) // check GET first
	{
		$id = mysql_escape_string($_PERMA[0]);
		
	}

	/*elseif ( REWRITE ) // check the URI if we're using mod_rewrite
	{
		$explodo = explode('/', $_SERVER['REQUEST_URI']);
		$id = mysql_escape_string($explodo[count($explodo)-1]);
	}*/
	else // otherwise, just make it empty
	{
		$id = '';
	}

	// if the id isnt empty and its not this file, redirect to its url
	if ( $id != '' && $id != basename($_SERVER['PHP_SELF']) )
	{
		$location = $url->get_url($id);
		if ( !empty($_PERMA[1]) )
		{
			$location = "$location/$_PERMA[1]";
		}
        if ( $location != -1 )
        {
			add_visits($id);
				if (preg_match("/\b.mp3\b/i", "$location") && MPLAY == true)
					{
						if (preg_match("/\b | \b/i", "$location"))
							{
								$msg = '<br /><div class=tip-display id=tip-display style=\"display:block;\" \"><object type="application/x-shockwave-flash" data="includes/player_mp3_multi.swf" width="200" height="100"><param name="movie" value="includes/player_mp3_multi.swf" /><param name="bgcolor" value="#424242" /><param name="FlashVars" value="mp3='.$location.'&amp;autoplay=1" /></object></div>';
							        
                                                                }else{
								$msg = '<br /><div class=tip-display id=tip-display style=\"display:block;\" \"><object type="application/x-shockwave-flash" data="includes/player_mp3_mini.swf" width="200" height="20"><param name="movie" value="includes/player_mp3_mini.swf" /><param name="bgcolor" value="#424242" /><param name="FlashVars" value="mp3='.$location.'&amp;autoplay=1" /></object><br /><a href="'.$location.'">'.$location.'</a></div>';
								
}
					}else{
					if (preg_match("/\b.flv\b/i", "$location") && VPLAY == true)
					{
						$msg = '<br /><div class=tip-display id=tip-display style="display:block;" ><object type="application/x-shockwave-flash" data="includes/player_flv_mini.swf" width="320" height="240" /><param name="allowFullScreen" value="true" /><param name="FlashVars" value="flv='.$location.'&amp;playercolor=3d3d3d" /></object><br /><a href="'.$location.'">'.$location.'</a></div>';
					}else{
					if (preg_match("/\b.jpg\b/i", "$location") || preg_match("/\b.JPG\b/i", "$location") || preg_match("/\b.png\b/i", "$location") || preg_match("/\b.PNG\b/i", "$location") || preg_match("/\b.gif\b/i", "$location") || preg_match("/\b.GIF\b/i", "$location") && LIMAGE == true)
					{
						$msg = '<br /><div class=tip-display id=tip-display style="display:block;" "><a href="'.$location.'"><img src="'.$location.'" width="400" /></a><br /><a href="'.$location.'">'.$location.'</a></div>';
					}else{
				if ( strtolower($_COOKIE['warn']) == 'true' )
					{
					 $msg = '<br/><div class=error-display id=success-display style=\"display:block;\" \"><h2>URL Preview</h2>You are about to continue to <a class="snap_shots" href="' . $location . ''.$qs.'">' . $location . ''.$qs.'</a><br/><i>Hover for a thumbnail preview</i><br/><br/><div class="snap_noshots"><div class="buttons"><a href="' . $location . ''.$qs.'">
Continue</a></div></div></div>';
					}else{
					header('Location: '.$location.''.$qs.'', TRUE, 301);
					}
						 }
		}
}		
}						
		else // failure to find url output 404
		{
			if (preg_match('/~/',$_SERVER['REQUEST_URI']))
				{
					$visitlink = explode( "~", $_PERMA[0], 3 );
					$visits = get_visits($visitlink[0]);
					$msg = '<br/><div class=tip-display id=tip-display style=\"display:block;\" \">The URL http://'.$_SERVER['SERVER_NAME'].'/'.$visitlink[0].' has been visited <b>'.$visits.'</b> times.</div>';
				}else{
			$msg = '<br/><div class=error-display id=error-display style=\"display:block;\" \">That URL does not exist. Try again?</div>';
			}
		}
	}
}

// print the form

?>

<?php include 'includes/header-one.php'; ?>
	
<body onload="document.getElementById('longurl').focus()">
		
<?php include 'includes/header-two.php'; ?>
		
		<?php echo $msg; ?>

<script>	
clip.addEventListener( 'onComplete', changeclipmsg );
function changeclipmsg( client, text ) { 
	$('div.clicktocopy').replaceWith('Copied to Clipboard');
};
</script>	

<div class="snap_noshots"><p><form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
		
			<fieldset>
				<label for="longurl">Enter a URL:</label>
				<input type="text" name="longurl" id="longurl" size="25" class="textbox"/><br />
<a href="#" id="open" onclick="show(this.id)">Choose a custom name<br /></a>
<div id="custom" style="display:none;">
<label for="plain"><?php include 'includes/config.php'; echo INSTALL_PATH; ?></label><input type="text" name="plain" id="plain" size="16" class="textbox-custom" /></div>
<div class="buttons"><button type="submit" class="positive" onclick="javascript:document.getElementById('once').disabled=true">Shorten</button><button type="reset" class="negative">Clear</button></div></fieldset>
<br/><div class="description"><?php if (RANDOM_DISPLAY==1) {include 'includes/random.php'; echo '<br/><br/>';} ?></div><b><?php include 'includes/counter.php'; ?></b> URLs shortened
		
		</form></p>

<?php include 'includes/footer.php'; ?></div>		
